class_name  Enemy
extends CharacterBody2D
var speed:=50

var maxHp=100
var health:=100:
	set(v):
		v=clampi(v,0,maxHp)
		health=v
var damege:=10

var dead=false
var player:Player=null

@onready var slime=$战利品
@export var itemRes:Item

@onready var detection=$Detection/CollisionShape2D
@onready var ani=$AnimatedSprite2D

func _ready() -> void:
	dead=false

func _physics_process(_delta: float) -> void:
	if dead:return
	if player:
		chase()
	else:
		ani.play('空闲')

# 追击
func chase(): 
	var dir=(player.position-position).normalized()
	velocity=dir*speed
	move_and_slide()
	ani.play('移动')

# 受伤
func getHurt(val):
	if dead:return
	health-=val
	# ani.play("受伤")
	if !health:deaded()

# 死亡
func deaded():
	if detection.disabled:return
	dead=true
	ani.play('死亡')
	await get_tree().create_timer(1).timeout
	drop()
	ani.visible=false
	detection.disabled=true
# 掉落
func drop():
	slime.visible=true
	collect()
# 添加到玩家背包
func collect():
	await get_tree().create_timer(1.5).timeout
	slime.visible=false
	get_parent().get_node('玩家').collect(itemRes)
	queue_free()

# 玩家检测
func _on_detection_body_entered(body:Node2D) -> void:
	if body is Player:player=body

func _on_detection_body_exited(body:Node2D) -> void:
	if body is Player:player=null

# 受伤检测
func _on_hurt_box_area_entered(area: Area2D) -> void:
	if area.name=='弓箭':getHurt(area.damage)
